<template>
  <h1>微博首页</h1>
  <div v-if="user==null">
    <router-link to="/reg">注册</router-link>
    |
    <router-link to="/login">登录</router-link>
  </div>
  <div v-else>
    <h2>欢迎{{ user.nickname }}回来!</h2>
    <el-button>
      <router-link to="/post" style="text-decoration: none;color: black">发布微博</router-link>
    </el-button>
    <el-button @click="logout()" style="color:black;">退出登录</el-button>
  </div>
  <hr>
  <div v-for="weibo in arr">
    <router-link :to="'/detail?id='+weibo.id" style="text-decoration: none;color:pink;">
      <h3>{{ weibo.nickname }}说:{{ weibo.content }}</h3>
    </router-link>
    <p>{{weibo.imgUrl}}</p>
    <img :src="'http://localhost:8080'+weibo.imgUrl" width="200">
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";

const arr = ref([]);
//所有进入页面就发请求的带写在此声明周期方法中
onMounted(() => {
  axios.get('http://localhost:8080/v1/weibos').then((response) => {
    if (response.data.code == 2001) {
      // 把服务器响应回来的微博数据装进数组中
      arr.value = response.data.data;
    }
  })
})

const logout = () => {
  if (confirm("您确认退出登录吗?")) {
    localStorage.clear();
    user.value = null;
  }
}
// 从localStorage获取用户数据,如果有需要将JSON格式字符串转成JS对象,没有则为null
let user = ref(localStorage.user ? JSON.parse(localStorage.user) : null);
</script>
